// heap-parser.ts

export interface HeapNode {
    id: string;
    name: string;
    type: string;
    totalSize: number;
    children: HeapNode[];
}

export interface HeapSnapshot {
    nodes: HeapNode[];
}

export function parseHeapSnapshot(raw: any): HeapSnapshot {
    const snapshot = raw.snapshot;
    const nodeFields = snapshot.meta.node_fields;
    const nodeTypes = snapshot.meta.node_types;
    const nodesArray = raw.nodes;
    const edgesArray = raw.edges;
    const strings = raw.strings || [];

    // 确定节点字段的偏移量
    const typeOffset = nodeFields.indexOf('type');
    const nameOffset = nodeFields.indexOf('name');
    const idOffset = nodeFields.indexOf('id');
    const sizeOffset = nodeFields.indexOf('self_size');
    const edgeCountOffset = nodeFields.indexOf('edge_count');
    const nodeStride = nodeFields.length;

    // 解析所有节点
    const nodes: HeapNode[] = [];
    for (let i = 0; i < snapshot.node_count; i++) {
        const base = i * nodeStride;
        const typeIndex = nodesArray[base + typeOffset];
        const nameIndex = nodesArray[base + nameOffset];

        nodes.push({
            id: nodesArray[base + idOffset].toString(),
            name: strings[nameIndex] || '',
            type: nodeTypes[0][typeIndex] || 'Unknown',
            totalSize: nodesArray[base + sizeOffset] || 0,
            children: []
        });
    }

    // 处理边关系
    const edgeFields = snapshot.meta.edge_fields;
    const edgeStride = edgeFields.length;
    const toNodeOffset = edgeFields.indexOf('to_node');
    let edgePointer = 0;

    for (let i = 0; i < nodes.length; i++) {
        const edgeCount = nodesArray[i * nodeStride + edgeCountOffset];
        const current = nodes[i];

        for (let e = 0; e < edgeCount; e++) {
            const edgeBase = edgePointer + e * edgeStride;
            const targetIndex = edgesArray[edgeBase + toNodeOffset];
            current.children.push(nodes[targetIndex]);
        }

        edgePointer += edgeCount * edgeStride;
    }

    return {nodes};
}